package com.jinlia.show.modules.base.utils;

import com.jinlia.show.modules.base.system.entity.Order;
import com.jinlia.show.modules.base.system.service.OrderMapperService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 付款单生成器
 */
public class OrderNumGenerator {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd"); // 2525年6月1日00:00:00
    private LocalDateTime lastLocalDateTime;

    private int currentSequence = 0;     // 当前序列号

    public OrderNumGenerator(OrderMapperService orderMapperService) {
        Order one = orderMapperService.lambdaQuery().select(Order::getOrderNum).orderByDesc(Order::getId).last("limit 1").one();
        if (one != null){
            String s = one.getOrderNum().split("S")[1];
            currentSequence = Integer.parseInt(s);
        }
        lastLocalDateTime = LocalDateTime.now() ;
    }

    public synchronized String nextId() {
        LocalDateTime now = LocalDateTime.now();
        // 检查时钟回拨
        if (now.isBefore(lastLocalDateTime)) {
            throw new RuntimeException(
                    String.format("Clock moved backwards. Refusing to generate id. Last time: %s, Current time: %s",
                            lastLocalDateTime, now)
            );
        }

        // 如果当前时间等于最后记录时间，则递增序列号

        if (now.getDayOfYear() == lastLocalDateTime.getDayOfYear()) {
            currentSequence++;
        } else {
            // 时间变化，重置序列号
            currentSequence = 0;
        }
        lastLocalDateTime = now;
        return String.format("%sS%s", formatter.format(lastLocalDateTime), currentSequence);
    }


    public static void main(String[] args) {
//        OrderNumGenerator idGenerator = new OrderNumGenerator();
//        for (int i = 0; i < 10; i++) {
//            new Thread(() -> {
//                for (int j = 0; j < 100; j++) {
//                    System.out.println(Thread.currentThread().getName()+idGenerator.nextId());
//                }
//            }).start();
////            System.out.println(Thread.currentThread().getName()+idGenerator.nextId());
//        }
    }
}
